package xyz.junerver.testcaptureandrecord.network;

import android.util.Log;

import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;

public class WebSocketManager {
    private final ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
    private final static String TAG = "CaptureScreen";
    private static WebSocketManager instance;
    private WebSocket webSocket;
    private OkHttpClient client;
    private String url;

    // 单例模式获取 WebSocketManager 实例
    public static synchronized WebSocketManager getInstance() {
        if (instance == null) {
            instance = new WebSocketManager();
        }
        return instance;
    }


    private WebSocketManager() {
        this.client = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .build();
    }

    public void setUrl(String url) {
        this.url = url;
    }

    // 建立 WebSocket 连接
    public void connect() {
        Request request = new Request.Builder().url(url).build();
        webSocket = client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                // 连接成功
                Log.e(TAG, "websocket连接成功");
                System.out.println("WebSocket Connected");
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                // 接收到消息
                System.out.println("Message Received: " + text);
            }

            // 在 onFailure 和 onClosed 方法中调用 reconnect
            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                Log.e(TAG, "websocket断开");
                System.err.println("WebSocket Failure: " + t.getMessage());
                reconnect(); // 连接失败后尝试重连
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                Log.e(TAG, "websocket断开");
                System.out.println("WebSocket Closed: " + reason);
                reconnect(); // 连接关闭后尝试重连
            }
        });
    }

    // 发送消息到 WebSocket
    public void sendMessage(String message) {
        if (webSocket != null) {
            webSocket.send(message);
        }
    }

    // 关闭 WebSocket 连接
    public void close() {
        if (webSocket != null) {
            webSocket.close(1000, "Normal Closure");
        }
    }

    // 重连机制
    private void reconnect() {
        // 尝试重新连接的逻辑，例如使用延迟重试
        // 使用 ScheduledExecutorService 调度任务
        scheduler.schedule(() -> {
            // 在这里放置您希望延迟执行的代码
            if (webSocket != null) {
                connect();
            }
        }, 1, TimeUnit.SECONDS); // 延迟 1 秒后执行
    }
}
